<template>
  <div class="main-container">

    <div class="mid-container2">
      <div class="video-container">
        <!--autoplay muted-->
        <video
          id="my-video"
          class="video-control"
          autoplay
          muted
          controls
        ></video>
      </div>
      <div class="input-container">
        <!-- <el-row class="row-sapn">
          <el-select
            v-model="brandtype"
            placeholder="请选择品牌"
            class="row-span"
            size="large"
          >
            <el-option
              v-for="item in brandoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-row> -->
        <!-- <el-row class="row-sapn">
          <el-select
            v-model="ip"
            placeholder="请选择摄像机或者录像机"
            class="row-span"
            size="large"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-row> -->
        <el-row class="row-sapn">
          <el-input
            v-model="deviceip"
            placeholder="请输入外场IP地址"
          ></el-input>
        </el-row>
        <el-row class="row-sapn" style="justify-content: center;">
          <el-button type="primary" @click="startRealPlay()"
            >实时流播放</el-button
          >
          <el-button type="primary" @click="stopRealPlay()">停止播放</el-button>
          
        </el-row>
        <el-row class="row-sapn" style="flex-direction: row;flex-wrap: nowrap;">
          <el-input
            v-model="address"
            placeholder="请输入地址"
          ></el-input>
          <!-- <el-button type="primary" @click="getPosition()"
          style="margin-left: 10px;">获取位置</el-button
          > -->
        </el-row>
        <el-row class="row-sapn" style="flex-direction: row;flex-wrap: nowrap;">
          <el-select
            v-model="violationType"
            placeholder="请选择违法类型"
            class="row-span"
            size="large"
          >
            <el-option
              v-for="item in violationOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button type="primary" @click="addressPush()"
             style="margin-left: 10px;">地址推送</el-button
          >
        </el-row>
        <!-- <el-row class="row-sapn">
          <el-date-picker
            v-model="timeSection"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-row>
        <el-row class="row-sapn">
          <el-col class="col-style">
            <label style="width: 80px">通道号</label>
            <el-input
              v-model="channel_value"
              placeholder="请输入通道号"
            ></el-input>
          </el-col>
        </el-row> -->
        <!-- <el-row class="row-sapn">
          <el-slider
            v-model="scale"
            show-stops
            :min="0.1"
            :max="1"
            :step="0.1"
          ></el-slider>
          <p>当前画面比例: {{ scale }}</p>
          <el-slider
            v-model="crf"
            show-stops
            :min="18"
            :max="51"
            :step="1"
          ></el-slider>
          <p>当前画面质量(越高越差): {{ crf }}</p>
        </el-row>
        <el-row class="row-sapn">
          <el-button type="primary" @click="startHistoryPlay()"
            >历史播放</el-button
          >
          <el-button type="primary" @click="stopHistoryPlay()"
            >停止播放</el-button
          >
        </el-row>
        <el-row class="row-sapn">
          <el-button type="primary" @click="historyDownload()"
            >历史下载</el-button
          >
        </el-row> -->
      </div>
    </div>
    <div class="footer"></div>
  </div>
</template>


<script>
import flvjs from "flv.js";
import axios from "axios";
import { parseTime } from "../utils/utils.js";
export default {
  data() {
    return {
      ip: "",
      deviceip: "",
      channel_value: 2,
      brandoptions: [
        { value: "1", label: "天地伟业" },
        { value: "2", label: "大华" },
        { value: "3", label: "海康" },
        { value: "4", label: "鼎尚铭星" },
        { value: "5", label: "宇视" },
      ],
      brandtype: null,
      //实时视频流端口无意义，添加只是为了区分下拉框的value
      options: [
        // { value: "192.168.1.202:3000", label: "tdwy录像机:192.168.1.202" },
        // { value: "192.168.1.201:80", label: "tdwy摄像头:192.168.1.201" },
        { value: "192.168.2.101:80", label: "tdwy摄像头:192.168.2.101" },
        // { value: "192.168.1.105:80", label: "摄像头:192.168.1.105" },
        //{ value: "192.168.1.142:81", label: "宇视摄像头:192.168.1.142" },
        { value: "192.168.2.101:81", label: "宇视摄像头:192.168.2.101" },
        { value: "192.168.2.101", label: "本地存储:192.168.2.101" },
        //{ value: "192.168.1.105", label: "本地存储:192.168.1.105" },
      ],
      violationType: "",//违法类型
      violationOptions: [
        { value: "1", label: "闯红灯" },
        { value: "2", label: "逆行" },
        { value: "4", label: "禁区" }
      ],
      address: "上海市浦东新区",
      flvPlayer: null,
      timer: null,
      video_token: "",
      video_url: "",
      lastDecodedFrame: 0,
      timeSection: [
        new Date(2024, 10, 19, 10, 0),
        new Date(2024, 10, 19, 10, 5),
      ],
      scale: 0.5,
      crf: 45,
    };
  },
  methods: {
    //初始化播放器
    initPlayer(_video_url, token) {
      if (flvjs.isSupported()) {
        console.log("flvjs支持,播放地址为：" + _video_url);
        const videoElement = document.getElementById("my-video");
        this.flvPlayer = flvjs.createPlayer(
          {
            type: "flv",
            cors: true,
            isLive: true,
            hasAudio: false,
            //必须与node搭建的流媒体服务器中的http的端口和推流的参数吻合
            url: _video_url,
          },
          {
            stashInitialSize: 128,
            enableWorker: false, //不启用分离线程
            enableStashBuffer: false, //关闭IO隐藏缓冲区
            reuseRedirectedURL: true, //重用301/302重定向url，用于随后的请求，如查找、重新连接等。
            autoCleanupSourceBuffer: true, //自动清除缓存
            headers: this.getHeader()
          }
        );
        this.flvPlayer.attachMediaElement(videoElement);
        this.attachPlayerEvent();
        this.flvPlayer.load();
        this.flvPlayer.play();
        return true;
      } else {
        console.log("flvjs不支持");
        return false;
      }
    },

    //加入事件
    attachPlayerEvent() {
      this.flvPlayer.on(flvjs.Events.LOADING_COMPLETE, (res) => {
        console.log("加载完成");
      });
      this.flvPlayer.on("error", (errorType, errorDetail, errorInfo) => {
        console.log("视频错误信息回调：");
        console.log("errorType:", errorType);
        console.log("errorDetail:", errorDetail);
        console.log("errorInfo:", errorInfo);
        this.deInitPlayer();
        console.log("断线重连......");
        this.initPlayer(this.video_url, this.video_token);
      });
      this.flvPlayer.on("statistics_info", (res) => {
        //在线卡顿的情况下，重连，但实际外场场景下会频繁重连
        // if (this.lastDecodedFrame == 0) {
        //   this.lastDecodedFrame = res.decodedFrames;
        //   return;
        // }
        // if (this.lastDecodedFrame != res.decodedFrames) {
        //   this.lastDecodedFrame = res.decodedFrames;
        // } else {
        //   console.info("视频卡顿了,重连接......");
        //   this.deInitPlayer();
        //   this.initPlayer(this.video_url, this.video_token);
        // }
      });
    },
    //销毁播放器
    deInitPlayer() {
      if (this.flvPlayer) {
        this.flvPlayer.pause();
        this.flvPlayer.unload();
        this.flvPlayer.detachMediaElement();
        this.flvPlayer.destroy();
        this.flvPlayer = null;
      }
    },

    //定时器发送心跳包
    sendHeartBeat(token) {
      this.timer = setInterval(() => {
        //console.log("sendHeartBeat token=" + token);
        axios
          .get("/apk/video/videoticket", {
            params: {
              ticketToken: token,
            },
            headers: this.getHeader()
          })
          .then((response) => {
            console.log("心跳包成功返回：" + JSON.stringify(response.data));
            if (response.data.code == 504) {
              console.info(
                "心跳包返回504，服务端推流完成，已经移除当前token,停止心跳包"
              );
              if (this.timer) {
                clearInterval(this.timer);
                this.timer = null;
              }
              this.deInitPlayer();
            }
          })
          .catch((error) => {
            console.log("心跳包请求失败：" + error);
          });
      }, 3 * 1000);
    },

    getHeader() {
      var header = null;
      if (this.deviceip != "") {
        header = {
          destip: this.deviceip,
        };
      }
      return header;
    },
    startRealPlay() {
      if (this.ip === "") {
        alert("请选择视频源");
        return;
      }
      // var device_ip = this.deviceip;
      // if (this.deviceip === '') {
      //   device_ip = this.ip;
      // }
      //先停止播放
      this.stopRealPlay();
      console.log("startPlay " + this.ip);
      //请求视频流参数
      axios
        .post(
          "/apk/video/realvideo",
          {
            ip: this.ip.split(":")[0],
            port: 80,
            channel: 0,
            scale: this.scale,
            crf: this.crf,
            rtmp: "flv",
          },
          { headers: this.getHeader() }
        )
        .then((response) => {
          console.log("实时视频播放请求：" + JSON.stringify(response.data));
          //初始化播放器
          if (response.data.code != 200) {
            alert("没有获取到视频流地址");
            return;
          }
          this.video_url = "." + response.data.result.url;
          this.video_token = response.data.result.ticketToken;
          if (this.initPlayer(this.video_url, this.video_token)) {
            this.sendHeartBeat(this.video_token);
          }
        });
    },
    stopRealPlay() {
      console.log("stopPlay");
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
      this.deInitPlayer();
      this.video_token = "";
      this.video_url = "";
      this.lastDecodedFrame = 0;
    },
    startHistoryPlay() {
      console.log("startHistoryPlay");
      if (this.ip === "") {
        alert("请选择视频源");
        return;
      }
      // var device_ip = this.deviceip;
      // if (this.deviceip === '') {
      //   device_ip = this.ip;
      // }
      if (
        this.timeSection[0] === undefined ||
        this.timeSection[1] === undefined
      ) {
        alert("请选择时间区间");
        return;
      }
      console.log(
        "startHistoryPlay: " +
          parseTime(this.timeSection[0]) +
          " - " +
          parseTime(this.timeSection[1])
      );
      axios
        .post(
          "/apk/video/history-play",
          {
            brand: this.brandtype,
            ip: this.ip,
            port: 3000,
            channel: this.channel_value,
            scale: this.scale,
            crf: this.crf,
            startTime: parseTime(this.timeSection[0]),
            endTime: parseTime(this.timeSection[1]),
          },
          { headers: this.getHeader() }
        )
        .then((response) => {
          console.log("历史视频播放请求：" + JSON.stringify(response.data));
          //初始化播放器
          if (response.data.code != 200) {
            alert(response.data.message);
            return;
          }
          this.video_url = "." + response.data.result.url;
          this.video_token = response.data.result.ticketToken;
          if (this.initPlayer(this.video_url, this.video_token)) {
            this.sendHeartBeat(this.video_token);
          }
        });
    },
    stopHistoryPlay() {
      console.log("stopHistoryPlay");
      axios
        .get(
          "/apk/video/stop-his-play",
          {
            params: {
              ticketToken: this.video_token,
            },
            headers: this.getHeader()
          }
        )
        .then((response) => {
          console.log("请求关闭视频流返回：" + JSON.stringify(response.data));
        })
        .catch((error) => {
          console.log("请求关闭视频流失败：" + error);
        });
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
      this.deInitPlayer();
      this.video_token = "";
      this.video_url = "";
      this.lastDecodedFrame = 0;
    },
    historyDownload() {
      console.log("historyDownload");
      if (this.ip === "") {
        alert("请选择视频源");
        return;
      }
      // var device_ip = this.deviceip;
      // if (this.deviceip === '') {
      //   device_ip = this.ip;
      // }
      if (
        this.timeSection[0] === undefined ||
        this.timeSection[1] === undefined
      ) {
        alert("请选择时间区间");
        return;
      }
      console.log(
        "historyDownload: " +
          parseTime(this.timeSection[0]) +
          " - " +
          parseTime(this.timeSection[1])
      );
      axios
        .post(
          "/apk/video/history-download",
          {
            brand: this.brandtype,
            ip: this.ip,
            port: 3000,
            channel: 0,
            fileName: "history.mp4",
            savePath: "/home/bdxhlog/",
            startTime: parseTime(this.timeSection[0]),
            endTime: parseTime(this.timeSection[1]),
          },
          { headers: this.getHeader() }
        )
        .then((response) => {
          console.log("历史视频下载请求：" + JSON.stringify(response.data));
          if (response.data.code == 200) {
            alert("视频下载成功");
          }

          //初始化播放器
          if (response.data.code != 200) {
            alert(response.data.message);
            return;
          }
        });
    },
    //地址推送
    addressPush() { 
      if(this.violationType == "") {
        alert("请选择违法类型");
        return;
      }
      if(this.address == "") {
        alert("请输入地址");
        return;
      }
      axios({
        method: "post",
        url: "/bik/api/bike-service/pushIllegalInfo",
        data: {
          description: this.address,
          illegal:this.violationType,
        },
      }).then((response) => {
        // console.log(response);
          // console.log("地址推送请求：" + JSON.stringify(response.data));
          if (response.data.code == 200) {
            alert("地址推送成功");
          } else {
            alert("地址推送失败：" + response.data.msg);
          }
        })  
    },
  },
  mounted() {
    console.log("mounted");
  },
};
</script>

<style scoped>
.el-input{
  min-height: 40px;
}
.el-button{
  min-height: 40px;
}
.main-container {
  height: 100vh;
  min-height: 100vh;
  position: relative;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}
.input-container{
  min-height: 30vh;
  background: lightyellow;
}
.header {
  flex: 0 0 auto;
  /* 设置容器的高度 */
  height: 10vh;
  /* 确保容器是一个块级元素，并且可以包含浮动元素 */
  display: flex;
  /* 垂直居中 */
  align-items: center;
  /* 水平居中（如果需要的话） */
  justify-content: center;
  /* 边框仅用于可视化效果 */
  background-color: lightblue;
  font-family: Arial, Helvetica, sans-serif;
  font-size: large;
}

.footer {
  flex: 0 0 auto;
  height: 5vh;
  background-color: lightgrey;
}

.row-sapn {
  margin: 5px;
}

.mid-container {
  flex: 1 1 auto;
  overflow-y: hidden;
  background-color: #d21212;
  position: relative;
  display: flex;
  flex-direction: row;
}

.col-style {
  display: flex;
  align-items: left;
}

.video-container {
  /* flex: 1 1 auto; */
  height: 70vh;
  overflow-y: hidden;
  background-color: #000;
}

/* 视频播放器 */
.video-control {
  width: 100%;
  height: 100%;
  background-color: black;
}
</style>